package com.zpf.web.servlet;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zpf.pojo.Address;
import com.zpf.pojo.Cart;
import com.zpf.pojo.Order;
import com.zpf.pojo.User;
import com.zpf.service.AddressService;
import com.zpf.service.CartService;
import com.zpf.service.OrderService;
import com.zpf.service.impl.AddressServiceImpl;
import com.zpf.service.impl.CartServiceImpl;
import com.zpf.service.impl.OrderServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@WebServlet("/orderservlet")
public class OrderServlet extends BaseServlet{

    CartService cartService = new CartServiceImpl();

    AddressService addressService = new AddressServiceImpl();

    OrderService orderService = new OrderServiceImpl();

    public String  paySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //获取支付结果
        String result = request.getParameter("result");

        //把json字符串转换成json对象
        Map map = JSON.parseObject(result, Map.class);

        JSONObject jsonObject = (JSONObject) map.get("result");
//获取支付结果
        String result_code = (String) jsonObject.get("result_code");
//如果支付成功，更新数据库的订单状态
        if("success".equalsIgnoreCase(result_code)){
//获取订单编号
            String out_trade_no = (String) jsonObject.get("out_trade_no");
            //更新订单状态
            Order order = new Order();
            order.setId(out_trade_no);
            order.setStatus("已支付");

            orderService.paySuccess(order);
        }

        request.setAttribute("msg","支付成功");
        return "forward:/message.jsp";
    }














//添加订单
    public String  addOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
//地址id
        String aid = request.getParameter("aid");

       Order order = orderService.addOrder(user.getId(),aid);
        request.setAttribute("order",order);
        return "forward:/orderSuccess.jsp";
    }



        //预览订单信息
    public String  getOrderView(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");


        //获取购物车信息
        List<Cart> carts = cartService.findCartByUid(user.getId());

        request.setAttribute("carts",carts);

        //查询该用户的地址列表信息
        List<Address> addList = addressService.findAddListByUid(user.getId());
        request.setAttribute("addList",addList);
        return "forward:/order.jsp";


    }
    }
